package wechat_service

import (
	"context"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/officialaccount"
	"github.com/silenceper/wechat/v2/officialaccount/basic"
	offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
	"github.com/silenceper/wechat/v2/officialaccount/message"
	"github.com/silenceper/wechat/v2/officialaccount/user"
	"github.com/spf13/viper"
	"go-beego-api/component/ck_log"
	"time"
)

type OfficialAccount struct {
	ctx             context.Context
	wc              *wechat.Wechat
	officialAccount *officialaccount.OfficialAccount
}

//NewOfficialAccount new
func NewOfficialAccount(ctx context.Context) *OfficialAccount {
	//init config
	offCfg := &offConfig.Config{
		AppID:          viper.GetString("wechat.official.appID"),
		AppSecret:      viper.GetString("wechat.official.appSecret"),
		Token:          viper.GetString("wechat.official.token"),
		EncodingAESKey: viper.GetString("wechat.official.encodingAESKey"),
	}
	wc := GetWechat()
	officialAccount := wc.GetOfficialAccount(offCfg)
	officialAccount.SetAccessTokenHandle(
		NewCkAccessToken(offCfg.AppID, offCfg.AppSecret, "niuren:official", GetCache()))
	return &OfficialAccount{
		ctx:             ctx,
		wc:              wc,
		officialAccount: officialAccount,
	}
}

func (s *OfficialAccount) GetQrCode(scene string) (qrCodeUrl string, err error) {
	req := basic.NewTmpQrRequest(1*600*time.Second, scene)
	tk, err := s.officialAccount.GetBasic().GetQRTicket(req)
	if err != nil {
		ck_log.LogCtx(s.ctx).Errorf("GetQr error, err=%+v", err)
		return
	}

	qrCodeUrl = basic.ShowQRCode(tk)
	return
}

func (s *OfficialAccount) GetOA() *officialaccount.OfficialAccount {
	return s.officialAccount
}

func (s *OfficialAccount) GetUserInfo(openID string) (userInfo *user.Info, err error) {
	return s.officialAccount.GetUser().GetUserInfo(openID)
}

func (s *OfficialAccount) SendTemplateMsg(openID string, templateID string) (msgID int64, err error) {
	data := map[string]*message.TemplateDataItem{}
	data["name"] = &message.TemplateDataItem{
		Value: "黄平",
		Color: "#173177",
	}
	msg := message.TemplateMessage{
		ToUser:     openID,
		TemplateID: templateID,
		Data:       data,
		//URL:        "https://www.niurentui.cn/wxa",
	}

	// 模版消息发送小程序链接, 需要同时满足以下三个条件
	// 1. 满足小程序已上线
	// 2. 小程序路径是已存在的
	// 3. 服务号与小程序绑定 (在设置->关联设置->关联的公众号中展示)  可以登录 “公众号管理后台-小程序管理” 完成关联

	// 因为这个测试小程序未上线，所以无法成功进行发送
	// 注释掉小程序链接, 则可以成功发送模版消息

	msg.MiniProgram.AppID = "wxa0d88c55d0176fd9"
	msg.MiniProgram.PagePath = "pages/index/index"

	return s.officialAccount.GetTemplate().Send(&msg)
}
